﻿CREATE PROCEDURE [dbo].[Text_Delete]
	@textId BIGINT
	,	@userId UNIQUEIDENTIFIER
	, @hashTag NVARCHAR(128)
AS
BEGIN
	DECLARE @order INT, @chapterId UNIQUEIDENTIFIER

	SET @hashTag = LOWER(@hashTag)

	BEGIN TRY
		BEGIN TRANSACTION
			SELECT @order = t.[Order], @chapterId = t.[ChapterId]
			FROM [dbo].[text_Text] AS t
			INNER JOIN [dbo].[text_Chapter] AS c ON t.[ChapterId] = c.[ChapterId]
			WHERE t.[TextId] = @textId AND c.[HashTag] = @hashTag

			IF @order IS NULL OR @chapterId IS NULL OR [dbo].[IsViewUnpublished](@userId) <> 1
			BEGIN
				ROLLBACK TRANSACTION
				RETURN
			END

			DELETE FROM [dbo].[text_Text]
			WHERE [TextId] = @textId

			UPDATE [dbo].[text_Text]
				 SET [Order] = [Order] - 1
			 WHERE [ChapterId] = @chapterId AND [Order] > @order
	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT	@ErrorMessage = ERROR_MESSAGE(),
						@ErrorSeverity = ERROR_SEVERITY(),
						@ErrorState = ERROR_STATE();

		RAISERROR (
								@ErrorMessage, -- Message text.
								@ErrorSeverity, -- Severity.
								@ErrorState -- State.
							);

	END CATCH

END